using System;
using Sce.PlayStation.Core.Environment;
using Sce.PlayStation.HighLevel.UI;

namespace Nyanimals
{
	public sealed class CGame
	{
        private static readonly CGame instance = new CGame();
        public static CGame Instance
        {
            get { return instance;}
        }
        
		private CStateMachine StateMachine;
		private CInput Input;
		private CRenderer renderer;
		
		private long lastTime;
		
		private bool bRunning;
        
		
		private CGame ()
		{
			Input = CInput.Instance;
			lastTime = DateTime.Now.Ticks;
			StateMachine = CStateMachine.Instance;
		}
		
        public void Stop()
        {
            bRunning = false;
        }
		public bool Running
		{
			get { return bRunning;}
		}
		
		public void Init()
		{
			// make sure the rnederer is made
			renderer = CRenderer.Instance;
			StateMachine.PushState(new CMainMenuState());
			bRunning = true;
		}
		
		public void Shutdown()
		{
			bRunning = false;
		}
		
		public void Update()
		{
			// time
			long nowTime = DateTime.Now.Ticks;
			double deltaTime = (nowTime - lastTime) / 10000000.0f;
			//Console.WriteLine(deltaTime.ToString());
			lastTime = nowTime;
			
			Input.Update();
			
			if(Input.ButtonReleased(Sce.PlayStation.Core.Input.GamePadButtons.Select))
			{
				bRunning = false;
			}
			
			StateMachine.Input();
			StateMachine.Update((float)deltaTime);
            CContextManager.Instance.FlushContext();            
            CEventManager.Instance.ProcessEvents();
            UISystem.Update(Input.TouchDataList);
		}
		
		public void Render()
		{
            CRenderer.Instance.Graphics.Clear();
            
			StateMachine.Render();
			CRenderer.Instance.Render();
		}
	}
}

